package note;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

@Slf4j
public class NoteConvertManage {

    /**
     * 从文件中读取文本到 List<String>
     */
    @SneakyThrows
    public List<String> readTxtFromFile(String filePathName) {
        Path path = Paths.get(filePathName);
        return Files.readAllLines(path);
    }

    /**
     * 将 List<String> 写入本地文本
     */
    @SneakyThrows
    public void writeListToTxt(List<String> txts, String filePathName) {
        for (String txt : txts) {
            Path path = Paths.get(filePathName, txt);
            if (Files.exists(path)) {
                Files.write(path, txt.getBytes());
            }
        }
    }

    /**
     * 处理列表内文本
     */
    public List<String> convertTxt(List<String> txts) {

        /* 移除符合 yyyy-mm-dd 格式的行 */

        for (int i = 0; i < txts.size(); i++) {
            if (i == 0) {
                /* book name */
                log.info("book name is: {}", txts.get(i));
            }
            if (i == 1 && txts.get(i) == null) {
                txts.remove(i);
                log.info("remove the second <null> line");
                i--;
            }
            if (i == 2) {
                /* book author */
                log.info("book author is: {}", txts.get(i));
                txts.add("\n\n");
                i = i + 2;
            }

        }
        return txts;
    }

    /**
     * 判断字符串是否为 yyyy-mm-dd 格式
     */
    public boolean isStrDateFormat(String input) {
        if (StringUtils.isBlank(input)) {
            return false;
        }
        try {
            String newInput = StringUtils.trim(input);
            DateUtils.parseDate(newInput, "yyyy-MM-dd");
            log.info("input {}", input);
            log.info("newInput {}", newInput);
            log.info("the line is date format, {}", input);
            return true;
        } catch (ParseException e) {
            return false;
        }

    }


}
